package com.yingli.network;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private TextView tvWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        tvWeb = findViewById(R.id.tv_web);
        Button btnRequest = findViewById(R.id.btn_httpclient);
        btnRequest.setOnClickListener(v -> {
            startActivity(new Intent(this,HttpClientActivity.class));
        });
        Button btnOKHttp = findViewById(R.id.btn_okhttp);
        btnOKHttp.setOnClickListener(v -> {
            startActivity(new Intent(this,HttpClientActivity.class));
        });
        Button btnAsyncTask = findViewById(R.id.btn_asynctask);
        btnAsyncTask.setOnClickListener(v -> {
            startActivity(new Intent(this,AsyncTaskActivity.class));
        });
        requestData();
    }

    private void initListener() {

    }

    private void initView() {
    }

    private Handler  handler = new Handler(Looper.getMainLooper()){
        //处理发送的消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //此处为携带的数据
            String data = (String) msg.obj;
            tvWeb.setText(data);
        }
    };

    private void requestData() {
        //Only the original thread that created a view hierarchy can touch its views.
        //只有最原始（主）线程才能修改UI
        new Thread(){
            @Override
            public void run() {
                super.run();
                HttpURLConnection urlConnection = null;
                try {
                    URL url = new URL("https://www.baidu.com");
                    urlConnection = (HttpURLConnection) url.openConnection();
                    //设置请求的方式为GET方式
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(3000);
                    //设置请求的编码方式
                    urlConnection.setRequestProperty("Charset", "UTF-8");
                    //设置请求文本类型为html格式的数据
                    urlConnection.setRequestProperty("Content-Type", "text/html;charset=utf-8;");
                    urlConnection.connect();
                    //获取请求响应码
                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode == 200) {
                        InputStream inputStream = urlConnection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuilder builder = new StringBuilder();
                        while (true) {
                            String temp;
                            if ((temp = reader.readLine()) != null) {
                                builder.append(temp);
                            }else {
                                break;
                            }
                        }
                        //方式一 通过Handler更新UI
//                        Message message = Message.obtain();
//                        message.obj = builder.toString();
//                        handler.sendMessage(message);
                        //lambda表达式
                        runOnUiThread(() -> {
                            tvWeb.setText(builder.toString());
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (urlConnection != null) {
                        urlConnection.disconnect();
                    }
                }
            }
        }.start();
    }
}